package common.store.admin.contoller;

import common.store.admin.dao.ProductDao;
import common.store.admin.dto.Category;
import common.store.admin.dto.Product;

import common.store.admin.service.CategoryService;
import common.store.admin.service.SupplierService;
import common.store.admin.service.impl.CategoryServiceImpl;
import common.store.admin.service.impl.SupplierServiceImpl;
import common.store.web.bean.Supplier;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;


@WebServlet("/upload")
public class AdminProductAddServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private CategoryService categoryService;

    private SupplierService supplierService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=UTF-8");
        categoryService = new CategoryServiceImpl();
        supplierService =new SupplierServiceImpl();
        List<Category> categoryList = categoryService.getCategoryList();
        //刷新列表页面的数据
        List<Supplier> supplierList=supplierService.getSupplierList();

        try {
            boolean isMultipart = ServletFileUpload.isMultipartContent(req);
            if (isMultipart){
                DiskFileItemFactory factory = new DiskFileItemFactory();

                ServletFileUpload upload = new ServletFileUpload(factory);

                factory.setSizeThreshold(10240); // 设置临时的缓冲文件大小为 10
                factory.setRepository(new File("D:\\IdeaProjects\\anotherStore\\store\\web\\products\\1")); // 设置临时文件的目录
                // 控制上传单个文件的大小 2MB
                upload.setSizeMax(2048000); // 字节B
                Thread.sleep(3000);
                String sname = null;

//                String pname = req.getParameter("pname");
//                String market_price = req.getParameter("marketPrice");
//                String shop_price = req.getParameter("shopPrice");
//                String is_hot = (req.getParameter("isHot"));
//                String pdesc = req.getParameter("pdesc");
//                String cid = req.getParameter("cid");
//                String s_id = req.getParameter("csid");
//                System.out.println(pname);
//                System.out.println(is_hot);
//                System.out.println(market_price);
//                System.out.println(shop_price);
                String pname = null;
                String market_price = null;
                String shop_price = null;
                String is_hot = null;
                String pdesc = null;
                String cid = null;
                String s_id = null;
                int cnt = 0;
                List<FileItem> items = upload.parseRequest(req);
                Iterator<FileItem> iter = items.iterator();
                Product product = new Product();
                while (iter.hasNext()){
                    FileItem item = iter.next();
                    String itemName = item.getFieldName();
                    int sno = -1;
                    String fileName;
                    if (item.isFormField()){
                        System.out.println(item.getFieldName());
                        if (item.getFieldName().equals("pname")){
                            pname = item.getString(); product.setPname(pname);
                        }
                        if (item.getFieldName().equals("marketPrice")){
                            market_price = item.getString();product.setMarketPrice(Double.valueOf(market_price));
                        }
                        if (item.getFieldName().equals("shopPrice")){
                            shop_price = item.getString();product.setShopPrice(Double.valueOf(shop_price));
                        }
                        if (item.getFieldName().equals("isHot")){
                            is_hot = item.getString();product.setIsHot(Integer.valueOf(is_hot));
                        }
                        if (item.getFieldName().equals("pdesc")){
                            pdesc = item.getString();product.setPdesc(pdesc);
                        }
                        if (item.getFieldName().equals("cid")){
                            cid = item.getString();product.setCid(cid);
                        }
                        if (item.getFieldName().equals("sid")){
                            s_id = item.getString();product.setSid(2);
                        }
//                        switch (item.getFieldName()){
//                            case "pname":pname = item.getString(); product.setPname(pname);
//                            case "marketPrice":market_price = item.getString();product.setMarketPrice(Double.valueOf(market_price));
//                            case "shopPrice":shop_price = item.getString();product.setShopPrice(Double.valueOf(shop_price));
//                            case "isHot":is_hot = item.getString();product.setIsHot(Integer.valueOf(is_hot));
//                            case "pdesc":pdesc = item.getString();product.setPdesc(pdesc);
//                            case "cid" : cid = item.getString();product.setCid(cid);
//                            case "csid":s_id = item.getString();
//                            case "sid":s_id = item.getString();product.setSid(Integer.valueOf(s_id));
//                            default: fileName = item.getName();
//                        }

                    }else {
                        fileName = item.getName();
                        String ext = fileName.substring(fileName.indexOf(".") + 1);
                        if (!(ext.equals("png") || ext.equals("gif") || ext.equals("jpg"))){
                            System.out.println("图片格式类型有误");
                            req.setAttribute("supplierList",supplierList);
                            req.setAttribute("categoryList" , categoryList);
                            req.setAttribute("msg", "图片格式类型有误！ 格式只能是 png gif jpg");
                            req.getRequestDispatcher("admin/product/add.jsp").forward(req , resp);
                            return;
                        }

                        String path = "D:\\IdeaProjects\\anotherStore\\store\\web\\products\\1";
                        File file = new File(path, fileName);

                        item.write(file);




//                        Product product = new Product();
//                        product.setCid(cid);
//                        product.setIsHot(Integer.valueOf(is_hot));
//                        product.setPdesc(pdesc);
//                        product.setMarketPrice(Double.valueOf(market_price));
//
//                        product.setPname(pname);
//
//                        product.setShopPrice(Double.valueOf(shop_price));
//                        product.setPid(UUID.randomUUID().toString().replaceAll("-" , ""));
//                        product.setSid(Integer.valueOf(s_id));

                        product.setPimage("products/1/"+fileName);
//                        ProductDao.updateProduct(product);
                        System.out.println(fileName + "上传成功！");

                        req.setAttribute("supplierList",supplierList);
                        req.setAttribute("categoryList" , categoryList);
                        req.setAttribute("msg", "上传成功！");


                        req.getRequestDispatcher("admin/product/add.jsp").forward(req , resp);

                    }

                }
                //todo: PID CID
                product.setPid(UUID.randomUUID().toString().replaceAll("-" , ""));
                product.setCid("2");
                System.out.println(product);
                ProductDao.insertProduct(product);
                req.setAttribute("supplierList",supplierList);
                req.setAttribute("categoryList" , categoryList);
                req.setAttribute("msg", "上传成功！");
                req.getRequestDispatcher("admin/product/add.jsp").forward(req , resp);


            }else {
                System.out.println("if not done");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        catch (FileUploadBase.SizeLimitExceededException e ){
            System.out.println("上传文件大小超过限制！最大 2MB");
            req.setAttribute("supplierList",supplierList);
            req.setAttribute("categoryList" , categoryList);
            req.setAttribute("msg", "上传文件大小超过限制！最大 2MB");
            req.getRequestDispatcher("admin/product/add.jsp").forward(req , resp);
        } catch (FileUploadException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
